﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
using System.Windows.Navigation;

namespace Sai_Se_Dung
{
    public partial class Play : PhoneApplicationPage
    {
        public static bool m_isEnded = false;
        public static bool m_isWinned = false;
        public static bool m_isNextLevel = false;

        public static DispatcherTimer m_timer;
        public static int m_time = 60;
        public static int m_level = 1;
        public static int m_num = 1;
        public static int m_score = 0;

        public static int m_curScore; // Show current Score to Lose Screen
        public static int m_curTime; // Show current excess Timer to add more bonus Score on Win Screen
        public static int m_curLevel;
        public static int m_curNum;

        public static bool isBacked = false;
        public static bool isTimeup = true; // Phát âm thanh hết thời gian 1 lần
        public static bool isHome = false;

        /// <summary>
        /// Constructor
        /// </summary>
        public Play()
        {
            InitializeComponent();

            SetDataContext();

            m_timer = new DispatcherTimer()
            {
                Interval = new TimeSpan(0, 0, 1)
            };
            m_timer.Tick += timer_Tick;

            // In case: level 2, level 3 when not bind data at first time
            txtTimer.Text = m_time.ToString();
        }

        #region Bựa chút thôi =))

        /// <summary>
        /// Constructor customize
        /// </summary>
        /// <param name="_level"></param>
        /// <param name="_score"></param>
        /// <param name="_num"></param>
        /// <param name="_time"></param>
        /// <param name="_isEnded"></param>
        /// <param name="_isWined"></param>
        /// <param name="_isNextLevel"></param>
        //public Play(int _level, int _score, int _num, int _time, bool _isEnded, bool _isWined, bool _isNextLevel)
        //{
        //    InitializeComponent();
        //    SetDataContext();

        //    m_level = _level;
        //    m_num = _num;
        //    m_score = _score;
        //    m_time = _time;
        //    m_isEnded = _isEnded;
        //    m_isWinned = _isWined;
        //    m_isNextLevel = _isNextLevel;

        //    m_timer = new DispatcherTimer()
        //    {
        //        Interval = new TimeSpan(0, 0, 1)
        //    };
        //    m_timer.Tick += timer_Tick;
        //}

        /// -------------------------------------------------------------------------
        /// code behind - not use here
        /// now use MVVM model (binding data: bind, observation, notify change,...)
        /// -------------------------------------------------------------------------
        //public void UpdateInfo()
        //{
        //    txtLevel.Text = m_level.ToString();
        //    txtScore.Text = m_score.ToString();
        //    txtNum.Text = m_num.ToString();
        //}

        #region Code behind
        private void btnB_Click(object sender, RoutedEventArgs e)
        {
            // If using MVVM, not recommend code behind
            // Let's synchronous them
        }

        private void btnA_Click(object sender, RoutedEventArgs e)
        {
            // If using MVVM, not recommend code behind
            // Let's synchronous them
        }
        #endregion

        #endregion

        /// <summary>
        /// Set data context to binding, load data
        /// </summary>
        public void SetDataContext()
        {
            LayoutRoot.DataContext = App.DataModel;
        }

        /// <summary>
        /// Override navigate page when direct to this
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //m_timer.Stop();
            m_timer.Start();
            m_isEnded = false;
            m_isWinned = false;

            switch (m_level)
            {
                case 1:
                    if (isBacked == false)
                    {
                        App.DataModel.LoadData();
                    }
                    break;
                case 2: // Không cần load lại câu hỏi
                    break;
                case 3: // Không cần load lại câu hỏi
                    break;
            }
        }

        /// <summary>
        /// Timer Tick
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)
        {
            txtTimer.Text = m_time.ToString();

            ///-----------------------------------------------------------------------------------------------------------
            #region Main Game Play Logic
            ///-----------------------------------------------------------------------------------------------------------

            if (m_isEnded == true)
            {
                m_timer.Stop();
                m_curScore = m_score;
                m_curNum = m_num;
                m_curTime = m_time;
                m_curLevel = m_level;
                //Reset(); --> Fix date 18/04
                NavigationService.Navigate(new Uri("/Lose.xaml", UriKind.Relative));
                m_isEnded = false;
            }
            else
            {
                switch (m_level)
                {
                    //---------------------------------------------------------------------------------------
                    case 1:
                        //---------------------------------------------------------------------------------------

                        m_time--;
                        // play count-down sound
                        if (m_time < 5 && m_time >= 0)
                        {
                            if (Option.isOn == true)
                            {
                                mp3_tick.Play();
                            }
                        }

                        if (m_time < 0)
                        {
                            mp3_tick.Stop(); // stop count-down sound
                            m_time = 0;
                            if (m_score < 80) // Support lose in case the player don't choose any answer
                            {
                                m_isEnded = true;
                            }
                            else //Level up
                            {
                                m_timer.Stop();
                                // Show current level, score on level up screen
                                m_curLevel = m_level;
                                m_curScore = m_score;
                                NavigationService.Navigate(new Uri("/LevelUp.xaml", UriKind.Relative));
                            }
                        }
                        break;

                    //---------------------------------------------------------------------------------------
                    case 2:
                        //---------------------------------------------------------------------------------------

                        m_time--;
                        if (m_time < 0)
                        {
                            if (m_num != 10) // Play time up sound
                            {
                                if (Option.isOn == true)
                                {
                                    mp3_timeup.Play();
                                }
                                m_isEnded = true;
                            }
                            m_time = 0;
                        }
                        break;

                    //---------------------------------------------------------------------------------------
                    case 3:
                        //---------------------------------------------------------------------------------------

                        m_time--;
                        if (m_time >= 0)
                        {
                            //Logic code here
                        }
                        else
                        {
                            // Play time up sound
                            if (isTimeup == true)
                            {
                                if (Option.isOn == true)
                                {
                                    mp3_timeup.Play();
                                }
                                isTimeup = false;
                            }

                            m_score -= 20;               // Subtract 20 scores per second
                            m_time = 0;                  // Time = 0

                            if (m_score > 0)
                            {
                                //Logic code here
                            }
                            else // m_score <= 0
                            {
                                mp3_timeup.Stop();      //Stop time up sound
                                m_score = 0;            // Score = 0
                                m_isEnded = true;       // Lose
                            }
                            // Show score count-down to zero
                            txtScore.Text = m_score.ToString();
                        }
                        break;
                }
            }

            // Next level from DataModel
            if (m_isNextLevel == true)
            {
                m_isNextLevel = false;
                // Show current level, score on level up screen
                m_curScore = m_score;
                m_curLevel = m_level;
                m_timer.Stop();
                NavigationService.Navigate(new Uri("/LevelUp.xaml", UriKind.Relative));
            }

            // Win
            if (m_isWinned == true)
            {
                m_curTime = m_time; // To add bonus score matching with excess time
                m_curScore = m_score; // Keep score before reset
                m_timer.Stop();
                NavigationService.Navigate(new Uri("/Win.xaml", UriKind.Relative));
                //Reset(); --> Fix date 18/04
            }

            #endregion
            ///-----------------------------------------------------------------------------------------------------------
        }

        /// <summary>
        /// Override method on BACK hard key of Phone
        /// </summary>
        /// <param name="e"></param>
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            SaveCurrentLevel();

            if (Option.isOn == true)
            {
                mp3_btn.Play();
            }
            
            if (NavigationService.CanGoBack)
            {
                while (NavigationService.RemoveBackEntry() != null)
                {
                    NavigationService.RemoveBackEntry();
                }
            }
            NavigationService.Navigate(new Uri("/Confirm.xaml", UriKind.Relative));

            SetCurrentLevel();

           // Reset();
        }

        /// <summary>
        /// Reset to level 1
        /// </summary>
        public void Reset()
        {
            m_timer.Stop();
            m_time = 60;
            m_level = 1;
            m_num = 1;
            m_score = 0;
            m_isEnded = false;
            m_isWinned = false;
            m_isNextLevel = false;
            App.DataModel.LoadData();
        }

        /// <summary>
        /// Resume current level
        /// </summary>
        public void SetCurrentLevel()
        {
            isBacked = true;
            m_timer.Stop();
            m_level = m_curLevel;
            m_time = m_curTime;
            m_num = m_curNum;
            m_score = m_curScore;
            m_isEnded = false;
            m_isWinned = false;
            m_isNextLevel = false;
        }

        private void btnHome_Click(object sender, RoutedEventArgs e)
        {
            if (Option.isOn == true)
            {
                mp3_btn.Play();
            }
            
            //isHome = true;
            //Play.m_timer.Stop();
            //SaveCurrentLevel();

            Reset();

            if (NavigationService.CanGoBack)
            {
                while (NavigationService.RemoveBackEntry() != null)
                {
                    NavigationService.RemoveBackEntry();
                }
            }
            NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative));
        }

        private void SaveCurrentLevel()
        {
            m_curScore = m_score;
            m_curNum = m_num;
            m_curTime = m_time;
            m_curLevel = m_level;
        }
    }
}